// 获取当前页面的分类
const getCurrentCategory = () => {
    const path = window.location.pathname;
    const filename = path.substring(path.lastIndexOf('/') + 1);
    const category = filename.replace('.html', '');
    
    // 映射文件名到实际分类名
    const categoryMap = {
        'frontend': '前端开发',
        'backend': '后端开发',
        'tools': '开发工具',
        'travel': '旅行日记',
        'food': '美食推荐'
    };
    
    return categoryMap[category] || category;
};

// 从localStorage加载文章
const loadArticles = () => {
    const articles = JSON.parse(localStorage.getItem('articles') || '[]');
    const currentCategory = getCurrentCategory();
    
    // 如果是首页，显示所有文章，否则按分类筛选
    const filteredArticles = currentCategory === 'index' 
        ? articles 
        : articles.filter(article => {
            console.log('比较:', article.category, currentCategory);
            return article.category === currentCategory;
        });
    
    // 按日期降序排序
    filteredArticles.sort((a, b) => new Date(b.date) - new Date(a.date));
    
    return filteredArticles;
};

// 渲染文章列表
const renderArticles = (articles) => {
    const articleList = document.getElementById('articleList');
    const noArticles = document.querySelector('.no-articles');
    
    if (!articles || articles.length === 0) {
        if (articleList) articleList.innerHTML = '';
        if (noArticles) noArticles.style.display = 'block';
        return;
    }
    
    if (noArticles) noArticles.style.display = 'none';
    if (articleList) {
        articleList.innerHTML = articles.map(article => `
            <article class="article-card">
                ${article.coverImage ? `
                    <img src="${article.coverImage}" alt="${article.title}" class="article-image">
                ` : ''}
                <div class="article-content">
                    <h3 class="article-title">${article.title}</h3>
                    <div class="article-excerpt">${marked.parse(article.content.substring(0, 200))}...</div>
                    <div class="article-meta">
                        <span class="article-date">${new Date(article.date).toLocaleDateString()}</span>
                        <span class="article-category">${article.category}</span>
                    </div>
                    ${article.tags && article.tags.length > 0 ? `
                        <div class="article-tags">
                            ${article.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}
                        </div>
                    ` : ''}
                </div>
            </article>
        `).join('');
    }
};

// 更新分类统计
const updateCategoryStats = () => {
    const articles = JSON.parse(localStorage.getItem('articles') || '[]');
    const stats = articles.reduce((acc, article) => {
        acc[article.category] = (acc[article.category] || 0) + 1;
        return acc;
    }, {});
    
    const statsList = document.querySelector('.stats-list');
    if (statsList) {
        statsList.innerHTML = Object.entries(stats).map(([category, count]) => `
            <li>
                <span>${category}</span>
                <span>${count}篇</span>
            </li>
        `).join('');
    }
};

// 更新标签云
const updateTagCloud = () => {
    const articles = JSON.parse(localStorage.getItem('articles') || '[]');
    const tagCounts = articles.reduce((acc, article) => {
        if (article.tags) {
            article.tags.forEach(tag => {
                acc[tag] = (acc[tag] || 0) + 1;
            });
        }
        return acc;
    }, {});
    
    const tagCloud = document.querySelector('.tag-cloud');
    if (tagCloud) {
        tagCloud.innerHTML = Object.entries(tagCounts).map(([tag, count]) => {
            const fontSize = Math.min(1 + (count * 0.2), 2); // 根据文章数量调整标签大小
            return `<a href="#" class="tag-item" style="font-size: ${fontSize}em">${tag}</a>`;
        }).join('');
    }
};

// 搜索功能
const setupSearch = () => {
    const searchInput = document.getElementById('search-input');
    const searchBtn = document.getElementById('search-btn');
    
    const performSearch = () => {
        const query = searchInput.value.toLowerCase();
        const articles = loadArticles();
        
        const filteredArticles = articles.filter(article => 
            article.title.toLowerCase().includes(query) ||
            article.content.toLowerCase().includes(query) ||
            (article.tags && article.tags.some(tag => tag.toLowerCase().includes(query)))
        );
        
        renderArticles(filteredArticles);
    };
    
    if (searchBtn) {
        searchBtn.addEventListener('click', performSearch);
    }
    
    if (searchInput) {
        searchInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                performSearch();
            }
        });
    }
};

// 初始化页面
document.addEventListener('DOMContentLoaded', () => {
    console.log('页面加载完成，开始初始化...');
    const articles = loadArticles();
    console.log('加载到的文章:', articles);
    renderArticles(articles);
    updateCategoryStats();
    updateTagCloud();
    setupSearch();
});

// 监听localStorage变化
window.addEventListener('storage', (e) => {
    if (e.key === 'articles') {
        const articles = loadArticles();
        renderArticles(articles);
        updateCategoryStats();
        updateTagCloud();
    }
}); 